package com.sy.service.impl.inventory;

import com.sy.bean.inventory.InventoryCont;
import com.sy.common.crud.BaseServiceImpl;
import com.sy.mapper.inventory.InventoryContMapper;
import com.sy.service.inventory.InventoryContService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.List;

@Service
public class InventoryContServiceImpl extends BaseServiceImpl<InventoryCont, InventoryContMapper> implements InventoryContService{


    String currentMaxCode; //当前最大编码 CG2024001

    @Autowired
    InventoryContMapper inventoryContMapper;

    @Override
    public List<InventoryCont> queryDetail(int id) {
        List<InventoryCont> list = inventoryContMapper.queryDetail(id);
        return list;
    }

    @Override
    public int insert(InventoryCont inventoryCont) {
        inventoryCont.setCode(generateCode());
        int rs = inventoryContMapper.insert(inventoryCont);
        if (rs == 0){
            throw new RuntimeException("保存盘点失败");
        }
        rs = inventoryContMapper.insertDetail(inventoryCont.getInventoryConDetailList());
        if (rs == 0){
            throw new RuntimeException("保存盘点明细失败");
        }
        return rs;
    }

    @Override
    public int delete(int id) {
        int rs = inventoryContMapper.delete(id);
        if (rs == 0){
            throw new RuntimeException("删除盘点失败");
        }
        rs = inventoryContMapper.deleteDetail(id);
        if (rs == 0){
            throw new RuntimeException("删除盘点明细失败");
        }
        return rs;
    }



    String generateCode() {
        String year = getYear();
        //判断当前最大编码是否存在
        if (null == currentMaxCode) {
            //如果不存在，查询当年最大编码
            currentMaxCode = baseMapper.queryMaxCode(year);
            if (null == currentMaxCode) {
                //说明不存在，生产第一个编码
                currentMaxCode = "PD" + year + "001";
            } else {
                //如果存在，新编码序号+1
                getNextCode();
            }
        } else {
            //如果存在，新编码序号+1
            getNextCode();
        }
        return currentMaxCode;
    }

    void getNextCode() {
        //CG2024001
        String prefix = currentMaxCode.substring(0, 6);
        String seq = currentMaxCode.substring(6);
        //转换数字001. tmp=1
        int tmp = Integer.parseInt(seq);
        tmp++;
        currentMaxCode = prefix + String.format("%03d", tmp);
    }

    String getYear() {
        LocalDate localDate = LocalDate.now();
        return String.valueOf(localDate.getYear());
    }


}
